package org.rabbitmq.mq02.mqServer.datacore;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.rabbitmq.mq02.common.MqException;
import org.rabbitmq.mq02.mqServer.core.Binding;
import org.rabbitmq.mq02.mqServer.core.Exchange;
import org.rabbitmq.mq02.mqServer.core.MSGQueue;
import org.rabbitmq.mq02.mqServer.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 对数据库中的Exchange,Queue,Binding和文件中的Message数据进行整合
 * 统一管理,后续上层代码直接调用该类中的方法即可,无需再向下层数据结构调用
 */
public class DiskDataManager {
    private DataBaseManager dataBaseManager = new DataBaseManager();
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    //交换机:
    //添加交换机
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }
    //删除交换机
    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }
    //查找交换机
    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }
    //队列
    //添加队列
    public void insertQueue(MSGQueue queue) throws IOException, MqException {
        dataBaseManager.insertQueue(queue);
        //创建队列后,不仅要将队列写入到数据库中,还要创建出对应的目录和文件
        messageFileManager.createQueueFile(queue.getName());
    }

    //删除队列
    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        //删除队列后,还要讲对应的目录和文件删除
        messageFileManager.destoryQueueFile(queueName);
    }
    //查找队列
    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueues();
    }
    //绑定关系
    //添加绑定关系
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }
    //删除绑定关系
    public void deleteBinding(String bingingKey){
        dataBaseManager.deleteBindings(bingingKey);
    }
    //查找绑定
    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBindings();
    }
    //消息
    //发送消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue,message);
    }

    //删除消息
    public void deleteMessageFromQueue(MSGQueue queue,Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessageFromFile(queue,message);
        //删除消息后,查看是否需要进行GC
        if(messageFileManager.checkGC(queue.getName())){
            messageFileManager.GC(queue);
        }
    }

    //加载所有的消息到内存中
    public List<Message> loadAllMessageFromQueue(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessage(queueName);
    }
}
